import requests
import pandas as pd
import xml.etree.ElementTree as ET
from datetime import datetime
import re


# Jenkins 服务器 URL 和认证信息
JENKINS_URL = 'https://xxxxx/'
JENKINS_USER = 'admin'
JENKINS_TOKEN = 'xxxxx'


# 获取所有任务名
def get_all_jobs():
    response = requests.get(f"{JENKINS_URL}/api/json", auth=(JENKINS_USER, JENKINS_TOKEN),  timeout=120, verify=False)
    jobs = response.json()['jobs']
    return [job['name'] for job in jobs]


# 获取任务最近的版本号
def get_last_build_info(job_name):
    response = requests.get(f"{JENKINS_URL}/job/{job_name}/api/json", auth=(JENKINS_USER, JENKINS_TOKEN), timeout=120, verify=False)
    json_response = response.json()
    last_build = json_response.get('lastBuild') if 'lastBuild' in json_response else None
    if last_build is None:
        last_build_number = 'N/A'
        last_build_time = 'N/A'
        branch_name = 'N/A'
    else:
        last_build_number = last_build.get('number', 'N/A')
        if last_build_number != 'N/A':
            build_info = requests.get(f"{JENKINS_URL}/job/{job_name}/{last_build_number}/api/json", auth=(JENKINS_USER, JENKINS_TOKEN)).json()
            timestamp = build_info.get('timestamp', 0)
            last_build_time = datetime.fromtimestamp(timestamp / 1000.0).strftime('%Y-%m-%d %H:%M:%S')
            actions = build_info.get('actions', [{}])
            for action in actions:
                if 'lastBuiltRevision' in action:
                    last_built_revision = action['lastBuiltRevision'].get('branch', [{}])
                    branch_name = last_built_revision[0].get('name', 'N/A') if last_built_revision else 'N/A'
                    break
                else:
                    branch_name = 'N/A'
        else:
            last_build_time = 'N/A'
            branch_name = 'N/A'
    return last_build_number, last_build_time, branch_name

# 获取任务配置中的信息
def get_job_config(job_name):
    response = requests.get(f"{JENKINS_URL}/job/{job_name}/config.xml", auth=(JENKINS_USER, JENKINS_TOKEN))
    root = ET.fromstring(response.content)
    git_address = base_img_addr = jar_name = war_name = 'N/A'
    liveness_probe = '否'

    for definition in root.iter('definition'):
        script_element = definition.find('script')
        if script_element is not None:
            script_content = script_element.text
            git_address_match = re.search(r'def git_address = "(.*?)"', script_content)
            base_img_addr_match = re.search(r'def base_img_addr = "(.*?)"', script_content)
            jar_name_match = re.search(r'jar_name = "(.*?)"', script_content)
            war_name_match = re.search(r'war_name = "(.*?)"', script_content)
            liveness_probe_match = re.search(r'livenessProbe', script_content)
            if git_address_match:
                git_address = git_address_match.group(1)
                print(git_address)
            else:
                print("git_address not found")
            if base_img_addr_match:
                base_img_addr = base_img_addr_match.group(1)
                print(base_img_addr)
            else:
                print("base_img_addr not found")
            if jar_name_match:
                jar_name = jar_name_match.group(1)
                print(jar_name)
            else:
                print("jar_name not found")
            if war_name_match:
                war_name = war_name_match.group(1)
                print(war_name)
            else:
                print("war_name not found")
            if liveness_probe_match:
                liveness_probe = '是'
                print(liveness_probe)
    return git_address, base_img_addr, jar_name, war_name, liveness_probe


# 收集所有数据
def collect_data():
    jobs = get_all_jobs()
    data = []

    for job in jobs:
        last_build_number, last_build_time, branch_name = get_last_build_info(job)
        git_address, base_img_addr, jar_name, war_name, liveness_probe = get_job_config(job)
        data.append([job, last_build_number, last_build_time, branch_name, git_address, base_img_addr, jar_name, war_name, liveness_probe])
        print(data)
    return data


# 转换为 DataFrame 并展示
def main():

    data = collect_data()
    df = pd.DataFrame(data, columns=['Job Name', 'Last Build Number', 'Last Build Time', 'Branch Name', 'Git Address', 'Base Image Address', 'Jar Name',
                                     'War Name', 'Liveness Probe'])
    df.to_excel('jenkins_data.xlsx', index=False)


if __name__ == '__main__':
    main()
